﻿using IService;
using Microsoft.AspNetCore.Mvc;
using Model;
using Service;
using System.Text.Json;

namespace WMS.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class BiSupplierController : Controller
    {
        private readonly IBiSupplierService _ibss;
        private readonly IDictService _dictService;
        private readonly ISysOrganizationService _orgService;
        private readonly IUsersService _userService;
        private readonly ILogger<BiSupplierController> _logger; // 注入日志服务

        public BiSupplierController(IBiSupplierService ibss, IDictService dictService,
            ISysOrganizationService orgService, IUsersService userService, ILogger<BiSupplierController> logger)
        {
            _ibss = ibss;
            _dictService = dictService;
            _orgService = orgService;
            _userService = userService;
            _logger = logger;
        }

        /// <summary>
        /// 获取字典数据（确保返回Code和Name）
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetDictData([FromQuery] string type)
        {
            try
            {
                List<WmsDictData> dictList = new List<WmsDictData>();
                switch (type)
                {
                    case "supplier_industry":
                        dictList = await _dictService.GetDictDataListAsync(6);
                        break;
                    case "supplier_type":
                        dictList = await _dictService.GetDictDataListAsync(7);
                        break;
                    case "supplier_status":
                        dictList = await _dictService.GetDictDataListAsync(2);
                        break;
                    default:
                        break;
                }
                // 映射为前端需要的Code和Name字段
                var result = dictList.Select(d => new {
                    Code = d.Code,
                    Name = d.Name
                }).ToList();
                return Ok(new { code = 200, data = result, msg = "查询成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"字典查询失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取组织机构树
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetOrgTree()
        {
            try
            {
                var orgTree = await _orgService.GetOrgTreeAsync();
                return Ok(new { code = 200, data = orgTree, msg = "查询成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = "查询失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 获取用户列表 - 真实数据版本
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetUsers([FromQuery] long? orgId = null)
        {
            try
            {
                List<Users> users;

                if (orgId.HasValue && orgId > 0)
                {
                    _logger.LogInformation("按部门查询用户，部门ID: {OrgId}", orgId);
                    users = await _userService.GetUsersByOrgIdAsync(orgId.Value);
                }
                else
                {
                    _logger.LogInformation("查询所有用户");
                    users = await _userService.GetAllAsync();
                }

                // 转换数据格式，优先使用真实姓名，如果没有则使用用户名
                var userList = users.Select(u => new
                {
                    id = u.UsersId,
                    name = !string.IsNullOrWhiteSpace(u.UsersTrueName) ? u.UsersTrueName : u.UsersName,
                    orgId = u.OrgId
                }).ToList();

                _logger.LogInformation("成功返回 {Count} 个用户数据", userList.Count);

                return Ok(new
                {
                    code = 200,
                    data = userList,
                    msg = userList.Count > 0 ? "查询成功" : "未找到用户数据"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户列表失败，部门ID: {OrgId}", orgId);

                return Ok(new
                {
                    code = 500,
                    data = new List<object>(),
                    msg = $"查询失败：{ex.Message}"
                });
            }
        }

        private async Task<string> GetOrgNameById(long? orgId)
        {
            try
            {
                if (!orgId.HasValue)
                    return "未分配部门";

                var org = await _orgService.GetByIdAsync(orgId.Value);
                return org?.OrgName ?? $"部门{orgId.Value}";
            }
            catch
            {
                return orgId.HasValue ? $"部门{orgId.Value}" : "未分配部门";
            }
        }

        /// <summary>
        /// 生成预览编码
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetPreviewCode()
        {
            try
            {
                var previewCode = await _ibss.GeneratePreviewCodeAsync();
                return Ok(new { success = true, code = previewCode });
            }
            catch (Exception ex)
            {
                return Ok(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 新增供应商
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] BiSupplier data)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage);
                    return BadRequest(new { code = 400, msg = "数据验证失败", errors = errors });
                }

                if (data == null || string.IsNullOrWhiteSpace(data.SupplierName))
                {
                    return Ok(new { code = 400, msg = "供应商名称不能为空" });
                }

                // 设置基础字段
                data.CreateTime = DateTime.Now;
                data.CreateBy = User.Identity?.Name ?? "system";
                data.IsDelete = "0";
                data.UpdateTime = DateTime.Now;
                data.UpdateBy = User.Identity?.Name ?? "system";

                // 设置默认值
                data.AttachmentId = data.AttachmentId ?? 0;
                data.Industry = data.Industry == 0 ? 1 : data.Industry;
                data.CustomerSource = data.CustomerSource == 0 ? 1 : data.CustomerSource;

                // 确保字符串字段不为null
                data.SupplierName = data.SupplierName?.Trim() ?? "";
                data.Status = data.Status ?? "1";
                data.ContactPerson = data.ContactPerson ?? "";
                data.ContactPhone = data.ContactPhone ?? "";
                data.Email = data.Email ?? "";
                data.Remarks = data.Remarks ?? "";
                data.AccountName = data.AccountName ?? "";
                data.TaxpayerId = data.TaxpayerId ?? "";
                data.BankAccount = data.BankAccount ?? "";
                data.OpeningBank = data.OpeningBank ?? "";
                data.BankAddress = data.BankAddress ?? "";

                var result = await _ibss.CreateAsync(data);

                if (result > 0)
                {
                    return Ok(new { code = 200, msg = "新增成功", data = result });
                }
                else
                {
                    return Ok(new { code = 500, msg = "新增失败" });
                }
            }
            catch (Exception ex)
            {
                var exceptionMessage = ex.Message;
                var innerException = ex.InnerException;
                while (innerException != null)
                {
                    exceptionMessage += " | " + innerException.Message;
                    innerException = innerException.InnerException;
                }

                return Ok(new { code = 500, msg = $"新增失败：{exceptionMessage}" });
            }
        }

        public IActionResult Index()
        {
            return View();
        }

        public async Task<IActionResult> Create()
        {
            await LoadDictDataToViewBag();
            return View();
        }

        private async Task LoadDictDataToViewBag()
        {
            try
            {
                // 所属行业字典
                var industryDictType = await _dictService.GetDictTypeAsync("sys_job_type");
                ViewBag.IndustryList = industryDictType != null
                    ? await _dictService.GetDictDataListAsync(industryDictType.DictTypeId)
                    : new List<WmsDictData>();

                // 供应商分类字典
                var supplierTypeDictType = await _dictService.GetDictTypeAsync("sys_supplier_type");
                ViewBag.SupplierTypeList = supplierTypeDictType != null
                    ? await _dictService.GetDictDataListAsync(supplierTypeDictType.DictTypeId)
                    : new List<WmsDictData>();

                // 进货部门字典
                var purchaseDeptDictType = await _dictService.GetDictTypeAsync("sys_purchase_dept");
                ViewBag.PurchaseDeptList = purchaseDeptDictType != null
                    ? await _dictService.GetDictDataListAsync(purchaseDeptDictType.DictTypeId)
                    : new List<WmsDictData>();

                // 状态字典
                var statusDictType = await _dictService.GetDictTypeAsync("sys_normal_statu");
                ViewBag.StatusList = statusDictType != null
                    ? await _dictService.GetDictDataListAsync(statusDictType.DictTypeId)
                    : new List<WmsDictData>();
            }
            catch
            {
                ViewBag.IndustryList = new List<WmsDictData>();
                ViewBag.SupplierTypeList = new List<WmsDictData>();
                ViewBag.PurchaseDeptList = new List<WmsDictData>();
                ViewBag.StatusList = new List<WmsDictData>();
            }
        }

        [HttpPost]
        public async Task<IActionResult> GetAllAsync()
        {
            var result = await _ibss.GetAllAsync();
            return Ok(new { code = 200, data = result, msg = "查询成功" });
        }

        public IActionResult Details()
        {
            return View();
        }

        /// <summary>
        /// 获取供应商详情（确保返回完整字段）
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Details(long id)
        {
            try
            {
                var supplier = await _ibss.GetByIdAsync(id);
                if (supplier == null)
                {
                    return Ok(new { code = 404, msg = "供应商不存在" });
                }
                return Ok(new
                {
                    code = 200,
                    data = supplier,
                    msg = "查询成功"
                });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询失败：{ex.Message}" });
            }
        }

        public IActionResult Edit(long id)
        {
            ViewBag.SupplierId = id;
            return View();
        }

        /// <summary>
        /// 更新供应商信息
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Edit(long id, [FromBody] BiSupplier data)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage);
                    return BadRequest(new { code = 400, msg = "数据验证失败", errors = errors });
                }

                // 确保ID一致性
                if (id != data.SupplierId)
                {
                    return Ok(new { code = 400, msg = "数据ID不一致" });
                }

                // 获取现有数据以确保有创建信息
                var existingSupplier = await _ibss.GetByIdAsync(id);
                if (existingSupplier == null)
                {
                    return Ok(new { code = 404, msg = "供应商不存在" });
                }

                // 保留创建信息
                data.CreateBy = existingSupplier.CreateBy;
                data.CreateTime = existingSupplier.CreateTime;
                data.IsDelete = existingSupplier.IsDelete;

                // 设置更新信息
                data.UpdateTime = DateTime.Now;
                data.UpdateBy = User.Identity?.Name ?? "system";

                var result = await _ibss.UpdateAsync(data);

                if (result > 0)
                {
                    return Ok(new { code = 200, msg = "更新成功", data = result });
                }
                else
                {
                    return Ok(new { code = 500, msg = "更新失败" });
                }
            }
            catch (Exception ex)
            {
                var exceptionMessage = ex.Message;
                var innerException = ex.InnerException;
                while (innerException != null)
                {
                    exceptionMessage += " | " + innerException.Message;
                    innerException = innerException.InnerException;
                }

                return Ok(new { code = 500, msg = $"更新失败：{exceptionMessage}" });
            }
        }

        public async Task<IActionResult> Delete(long id)
        {
            try
            {
                if (id <= 0)
                {
                    return Ok(new { code = 400, msg = "无效的供应商ID" });
                }

                var existing = await _ibss.GetByIdAsync(id);
                if (existing == null)
                {
                    return Ok(new { code = 404, msg = "供应商不存在" });
                }

                if (existing.IsDelete == "1")
                {
                    return Ok(new { code = 400, msg = "供应商已被删除" });
                }

                var result = await _ibss.DeleteAsync(id);

                if (result > 0)
                {
                    return Ok(new { code = 200, data = result, msg = "删除成功" });
                }
                else
                {
                    return Ok(new { code = 500, msg = "删除失败：未影响任何数据" });
                }
            }
            catch (Exception ex)
            {
                var exceptionMessage = ex.Message;
                var innerException = ex.InnerException;
                while (innerException != null)
                {
                    exceptionMessage += " | " + innerException.Message;
                    innerException = innerException.InnerException;
                }
                return Ok(new { code = 500, msg = $"删除失败：{exceptionMessage}" });
            }
        }

        /// <summary>
        /// 导出选中供应商数据为Excel
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Export([FromBody] List<long> supplierIds)
        {
            try
            {
                if (supplierIds == null || supplierIds.Count == 0)
                    return Ok(new { code = 400, msg = "请选择需要导出的数据" });

                var stream = await _ibss.ExportAsync(supplierIds);
                var fileName = $"供应商数据_{DateTime.Now:yyyyMMddHHmmss}.xlsx";

                // 响应Excel文件，触发下载到桌面
                return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"导出失败：{ex.Message}" });
            }
        }


    }
}